<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Crypt;
use Session;

class LoginController extends Controller
{
    //显示登录也页面
    public function login(Request $request)
    {	
    	if($request -> isMethod('POST'))
        {   
            //检测cookie有没有值
            $isLogin = \Cookie::get('isLogin');
            if($isLogin)
            {   
                $res = DB::table('users') -> where('email', $isLogin) -> first();
                Session::put('user_master', $res);
                return redirect('/home/index') -> with(['info' => '登陆成功']);
            }

            //表单显示帐号
            $request -> flashOnly('email');

            //验证码
            $code = $request -> input('code');
            if($code != Session::get('code'))
            {
                return back() -> with(['info' => '验证码错误']);
            }

            // 验证邮箱和密码
            $email = $request -> input('email');
            $res = DB::table('users') -> where('email', $email) -> first();
            if(!$res)
            {
                return back() -> with(['info' => '用户名不正确']);
            }

            //解密
            $password = Crypt::decryptString($res -> password);
            if($request -> input('password') != $password)
            {
                return back() -> with(['info' => '用户名或者密码错误']);
            }

            //判断是否记住我
            if($request -> has('checkMe'))
            {
                \Cookie::queue('isLogin', $res -> name, 60 * 24);
            }

            Session::put('user_master', $res);
            return redirect('/home/index') -> with(['info' => '登陆成功']);
        }else
        {
            return view('home.login.index', ['title' => '登录']);
        } 	   		
 	}  

 	 //用户退出设置
    public function logout()
    {
    	Session::forget('user_master');
    	return redirect('/home/login') -> with(['info' => '退出成功']);
    } 
}
